<template>
  <div class="complierBox">
    <div class="selection">
      <el-select
        class="n-select"
        placeholder="语言"
        size="small"
        v-model="userEditData.language"
      >
        <el-option
          v-for="item in languageList"
          :key="item.id"
          :label="item.language"
          :value="item.language"
        ></el-option>
      </el-select>
      <div class="selection-right">
        <el-tooltip content="重置代码">
          <i class="iconfont icon-htmal5icon23" @click="resetCode()"></i>
        </el-tooltip>
        <el-tooltip content="设置编译器">
          <i class="iconfont icon-shezhi" @click="isShowEdit = true"></i>
        </el-tooltip>
        <el-tooltip content="全屏">
          <i class="iconfont icon-suoxiao1" @click="toAllScreen()"></i>
        </el-tooltip>
      </div>
      <n-modal v-model:show="isShowEdit">
        <n-card
          :bordered="false"
          role="dialog"
          aria-modal="true"
          class="card"
          :style="{
            height: $store.oj.getCardHeight,
            width: $store.oj.getCardWidth,
          }"
        >
          <h2 class="title">
            编译器设置<span @click="isShowEdit = false"
              ><i class="iconfont icon-chahao1"></i
            ></span>
          </h2>
          <div class="e-item">
            字体设置:<n-select
              class="n-select"
              size="tiny"
              v-model:value="fontSize"
              :options="fontSizeList"
            ></n-select>
          </div>
          <div class="e-item">
            主题设置:<n-select
              class="n-select"
              size="tiny"
              v-model:value="theme"
              :options="themeList"
            ></n-select>
          </div>
        </n-card>
      </n-modal>
    </div>
    <n-split
      direction="vertical"
      :style="{ height: '97%' }"
      :max="0.9"
      :min="0.25"
      :default-size="0.9"
    >
      <template #1>
        <codeMirrorTreeCM
          :language="userEditData.language"
          :type="$props.problemType"
          :fontSize="fontSize"
          :value="userEditData"
          @valueChange="
            (value) => {
              userEditData = { ...value };
            }
          "
        >
        </codeMirrorTreeCM>
      </template>
      <template #2>
        <div class="submit">
          <div>
            <div class="s-bar">
              <transition>
                <n-button
                  id="submitResult"
                  class="loading"
                  :type="finalType"
                  size="small"
                  :disabled="isShowResult"
                  v-show="isShowJudgingBtn"
                  @click="handlerToDetail()"
                >
                  <i
                    class="iconfont icon-jiazai loading-icon"
                    v-show="isShowResult"
                  ></i>
                  <div v-show="!isShowResult">
                    <i class="iconfont icon-ai53" v-show="finalStats == 0"></i>
                    <i
                      class="iconfont icon-chahao"
                      v-show="finalStats != 0"
                    ></i>
                  </div>
                  <div v-show="isShowResult">评测中</div>
                  <div v-show="!isShowResult">
                    {{ statusToWord(finalStats) }}
                  </div>
                </n-button>
              </transition>
              <div class="isLoginPanel" v-show="!$store.oj.isLogin">
                <i class="iconfont icon-jinggao"></i> 请登陆后提交
              </div>
              <n-button
                class="n-btn1"
                size="small"
                v-show="$store.oj.isLogin"
                :disabled="isSubmitDebugReady || raceStatus.type == 1"
                @click="submitDebug(), (activeName = 'one')"
                ><i class="iconfont icon-bug"></i> 运行</n-button
              >
              <n-button
                class="n-btn2"
                size="small"
                v-show="$store.oj.isLogin"
                :disabled="isShowResult"
                type="primary"
                @click="submit()"
                ><i class="iconfont icon-chuanshuliebiao"></i>提交</n-button
              >
            </div>
            <div class="s-contain" v-loading="loading">
              <el-tabs v-model="activeName">
                <el-tab-pane name="one">
                  <template #label>
                    <span>运行结果</span>
                  </template>
                  <el-scrollbar class="s-c-scrollbar">
                    <transition>
                      <div v-show="debugData.status == null" class="nodata">
                        保存并提交之后，这里将会显示运行结果
                      </div>
                    </transition>
                    <transition>
                      <div class="accept" v-show="debugData.status == 0">
                        <div class="a-text">运行成功</div>
                        <div>
                          Tips :
                          自测用例通过仅代表自测时使用的数据通过，不代表题目的测试用例均能通过。
                        </div>
                      </div>
                    </transition>
                    <transition>
                      <div class="output" v-show="debugData.status == 0">
                        <div class="o-text">
                          自测输入
                          <div class="text">{{ inputData }}</div>
                        </div>
                        <div class="o-text">
                          实际输出
                          <div class="text">{{ debugData.outputData }}</div>
                        </div>
                      </div>
                    </transition>
                    <transition>
                      <div
                        class="card2"
                        :class="getBarColor(debugData.status)"
                        v-show="
                          debugData.status != null && debugData.status != 0
                        "
                      >
                        <div class="bar">
                          {{ statusToWord(debugData.status) }}
                        </div>
                        <div class="contain">
                          <span>
                            {{ debugData.errorMessage }}
                          </span>
                        </div>
                      </div>
                    </transition>
                  </el-scrollbar>
                </el-tab-pane>
                <el-tab-pane name="two">
                  <template #label>
                    <span>自测输入</span>
                  </template>
                  <el-input
                    class="textarea"
                    maxlength="100"
                    :autosize="{ minRows: 6, maxRows: 9 }"
                    type="textarea"
                    placeholder=""
                    v-model="inputData"
                  ></el-input>
                </el-tab-pane>
              </el-tabs>
            </div>
          </div>
        </div>
      </template>
    </n-split>
  </div>
</template>

<script>
import codeMirrorTreeCM from "./codeMirrorTreeCM.vue";
import {
  submitAPI,
  submitDebugAPI,
  getDebugDetailAPI,
  getDetailBySubmitIdAPI,
  userSubmitRaceAPI,
  getCodeTempaletAPI,
} from "@/api/ojAPI/ojAPI";
import { ElMessage } from "element-plus";
import { statusToWords } from "@/utils/global.js";

import { fontSizeListConf, themeListConf } from "../config";
export default {
  data() {
    return {
      codeTemplate: "",
      languages: [],
      isShowEdit: false,
      fontSizeList: fontSizeListConf,
      themeList: themeListConf,
      theme: "3024-day",
      fontSize: "16px",
      userEditData: {
        pid: "",
        code: "",
        language: "",
        format: [],
      },
      isShowJudgingBtn: false,
      JudgedStatus: null,
      isShowResult: false,
      finalStats: null,
      finalType: "",
      submitId: -1,
      timer: null,
      raceStatus: {
        type: null,
        state: null,
      },
      codeTemplateList: {},
      debugId: null,
      debugData: {
        status: null,
        errorMessage: null,
        outputData: null,
      },
      isSubmitDebugReady: false,
      inputData: "",
      loading: false,
      activeName: "one",
      isAllScreen: false,
      duration: 0,
      durationTime: 2000,
    };
  },
  components: {
    codeMirrorTreeCM,
  },
  async mounted() {
    await this.getCodeTempalet(this.pid);
    this.userEditData.pid = this.pid;
  },
  props: ["pid", "languageList", "problemType"],
  emits: ["allScreen"],
  methods: {
    submit() {
      this.duration = Date.now();
      this.isShowJudgingBtn = false;
      this.finalType = "";
      this.finalStats = null;
      if (this.userEditData.code.length === 0 && this.problemType == 0) {
        ElMessage.error("无代码输入");
        return;
      }
      if (!this.userEditData.language) {
        ElMessage.error("请选择语言");
        return;
      }
      const postData = {
        ...this.userEditData,
        code: JSON.stringify(this.userEditData.code),
      };

      //比赛判题
      if (this.$route.name == "raceing-quiz") {
        userSubmitRaceAPI(
          this.$route.params.rid,
          this.$route.query.proId,
          postData
        )
          .then((res) => {
            if (res.data.code === 200) {
              const str = localStorage.getItem(
                `${this.$route.params.rid}format`
              );
              this.raceStatus.type = str;
              if (this.raceStatus.type == 1) {
                //oi赛制
                this.isShowJudgingBtn = true;
                this.finalType = "success";
                this.finalStats = 0;
                console.log(this.finalType, this.finalStats);
              } else {
                //ACM IOI
                ElMessage.warning("评测中");
                this.isShowJudgingBtn = true;
                this.finalType = "info";
                this.isShowResult = true;
                this.submitId = res.data.data?.submitId;
                if (this.submitId)
                  this.getDetailBySubmitId(res.data.data.submitId);
              }
            }
          })
          .catch((err) => {
            ElMessage.error("系统错误");
          });
      } else {
        //普通判题
        let data = {};
        if (this.problemType == 0) {
          data = {
            pid: this.userEditData.pid,
            language: this.userEditData.language,
            code: JSON.stringify(this.userEditData.code),
          };
        } else {
          const codeRes = [];
          const findleave = (tree, stack) => {
            for (const node of tree) {
              if (node.type == "file") {
                codeRes.push({
                  fileName: stack.length
                    ? stack.join("/") + "/" + node.label
                    : node.label,
                  content: node.code,
                });
                stack.pop();
              } else {
                stack.push(node.label);
                findleave(node.children, stack);
              }
            }
          };
          findleave(this.userEditData.format, []);
          data = {
            pid: this.userEditData.pid,
            language: this.userEditData.language,
            code: JSON.stringify(codeRes),
          };
        }
        submitAPI(data)
          .then((res) => {
            if (res.data.code === 200) {
              ElMessage.warning("评测中");
              this.isShowJudgingBtn = true;
              this.finalType = "info";
              this.isShowResult = true;
              this.submitId = res.data.data.submitId;
              this.getDetailBySubmitId(res.data.data.submitId);
            }
          })
          .catch((err) => {
            ElMessage.error("系统错误");
          });
      }
    },
    submitDebug() {
      if (this.userEditData.code.length === 0 && this.problemType == 0) {
        ElMessage.error("无代码输入");
        return;
      }
      if (!this.userEditData.language) {
        ElMessage.error("请选择语言");
        return;
      }
      let data = {};
      if (this.problemType == 0) {
        data = {
          pid: this.userEditData.pid,
          language: this.userEditData.language,
          code: JSON.stringify(this.userEditData.code),
        };
      } else {
        const codeRes = [];
        const findleave = (tree, stack) => {
          for (const node of tree) {
            if (node.type == "file") {
              codeRes.push({
                fileName: stack.length
                  ? stack.join("/") + "/" + node.label
                  : node.label,
                content: node.code,
              });
              stack.pop();
            } else {
              stack.push(node.label);
              findleave(node.children, stack);
            }
          }
        };
        findleave(this.userEditData.format, []);
        data = {
          pid: this.userEditData.pid,
          language: this.userEditData.language,
          code: JSON.stringify(codeRes),
        };
      }
      submitDebugAPI({
        ...data,
        inputData: this.inputData,
      }).then((res) => {
        this.isSubmitDebugReady = true;
        this.loading = true;
        const str = localStorage.getItem(`${this.$route.params.rid}format`);
        this.raceStatus.type = str;
        if (this.raceStatus.type == 1) {
          return;
        }
        if (res.data.code === 200) {
          this.debugId = res.data.data;
          this.getDebugDetail();
        }
      });
    },
    getDetailBySubmitId(id) {
      getDetailBySubmitIdAPI(id)
        .then((res) => {
          if (res.data.code === 200) {
            if (res.data.data.status > 10) {
              setTimeout(
                () => {
                  this.getDetailBySubmitId(id);
                },
                this.duration > 3000
                  ? 3000
                  : this.durationTime < 1000
                  ? 1000
                  : this.durationTime
              );
            } else {
              this.isShowResult = false;
              this.finalStats = res.data.data.status;
              if (this.finalStats == 0) {
                this.finalType = "success";
                this.runAnimation();
              } else if (this.finalStats == 8 || this.finalStats == 6) {
                this.finalType = "warning";
              } else if (this.finalStats == 5) {
                this.finalType = "tertiary";
              } else if (this.finalStats == 1) {
                this.finalType = "info";
              } else {
                this.finalType = "error";
              }
              this.durationTime = Number(
                ((Date.now() - this.duration) / 3).toFixed(0)
              );
            }
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    statusToWord(value) {
      if (this.raceStatus.type == 1) {
        return "提交成功";
      }
      return statusToWords(value);
    },
    handlerToDetail() {
      if (this.raceStatus.type == 1) {
        return;
      }
      if (!this.submitId) {
        return;
      }
      if (this.isShowResult) {
        return;
      }
      if (this.$route.name == "raceing-quiz") {
        this.$router.push(
          `/home/racepage/${this.$route.params.rid}/evaluation/${this.submitId}`
        );
        return;
      }
      this.$router.push({
        path: `/home/evaluation-detail/${this.submitId}`,
      });
    },
    //本地缓存用户代码
    setCodeLocal(code) {
      if (this.timer) {
        clearTimeout(this.timer);
      }
      if (
        this.$route.name == "raceing-quiz" &&
        this.$route.params.pid &&
        this.$route.params.rid
      ) {
        this.timer = setTimeout(() => {
          localStorage.setItem(
            `${this.$route.params.pid}${this.$route.params.rid}`,
            code
          );
        }, 300);
      } else {
        this.timer = setTimeout(() => {
          localStorage.setItem(`${this.userEditData.pid}`, code);
        }, 300);
      }
    },
    //获取已存在的缓存数据
    getCodeLocal() {},
    resetCode() {
      if (this.codeTemplateList[this.userEditData.language]) {
        this.userEditData.code = "";
        this.userEditData.format = JSON.parse(
          this.codeTemplateList[this.userEditData.language].format
        );
        return;
      }
      this.userEditData.code = "";
      this.userEditData.format = [];
    },
    async getCodeTempalet(pid) {
      await getCodeTempaletAPI(pid)
        .then((res) => {
          if (res.data.code === 200) {
            this.codeTemplateList = res.data.data;
          }
          this.getCodeLocal();
        })
        .catch((err) => {
          console.log(err);
        });
    },
    runAnimation() {
      const ele = document.getElementById("submitResult");
      const { x, y } = ele.getBoundingClientRect();
      confetti({
        particleCount: 150, //粒子数量
        spread: 60, //粒子速度
        origin: {
          //初始位置
          x:
            (x + this.$store.oj.systemParams.screenWidth / 30) /
            this.$store.oj.systemParams.screenWidth,
          y: y / this.$store.oj.systemParams.screenHeight,
        },
      });
    },
    handlerToChangeHeight(event) {
      document.addEventListener("mousemove", this.handlerToChangeHeight);
      document.addEventListener("mouseup", this.handlerToNotChangeHeight);
      this.height = this.getHeightRate(
        this.$store.oj.systemParams.screenHeight,
        event.clientY
      );
    },
    handlerToNotChangeHeight() {
      document.removeEventListener("mousemove", this.handlerToChangeHeight);
    },
    getDebugDetail() {
      getDebugDetailAPI(this.debugId).then((res) => {
        if (res.data.code == 200) {
          if (res.data.data.status == null || res.data.data.status > 10) {
            setTimeout(() => {
              this.getDebugDetail();
            }, 1000);
          } else {
            this.debugData = res.data.data;
            this.isSubmitDebugReady = false;
            this.loading = false;
          }
        }
      });
    },
    getBarColor(value) {
      if (value == 0) {
        return "greenBar";
      } else if (value === -1 || (value > 1 && value != 8 && value != 6)) {
        return "redBar";
      } else if (value === 8 || value === 6) {
        return "orangeBar";
      }
      return "";
    },
    toAllScreen() {
      this.$emit("allScreen");
    },
  },
  watch: {
    languageList: function (newV, oldV) {
      if (newV) {
        let flag = 0;
        newV.forEach((ele) => {
          if (ele.language == this.userEditData.language) {
            flag = 1;
          }
        });
        if (flag == 0) {
          this.userEditData.language = newV[0].language;
          if (this.codeTemplateList[this.userEditData.language])
            this.userEditData.format = JSON.parse(
              this.codeTemplateList[this.userEditData.language].format
            );
          return;
        }
      }
    },
  },
};
</script>

<style lang="less" scoped>
.card {
  border-radius: 20px;
  overflow: hidden;

  .title {
    border-bottom: 1px solid @bgColor;
    padding-bottom: 10px;
    display: flex;

    span {
      font-size: 16px;
      color: #888;
      margin: auto 1vw auto auto;

      &:hover {
        color: rgb(115, 193, 50);
        cursor: pointer;
      }
    }
  }

  .e-item {
    margin: 10px 0;
    width: 100%;
    height: 30px;
    display: flex;
    padding-left: 20px;

    .n-select {
      width: 20%;
      margin: auto 20px;
    }
  }
}

::-webkit-scrollbar(.complierBox) {
  display: none;
}

.complierBox {
  height: 85vh;
  width: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;

  .selection {
    min-height: 35px;
    height: 5.5vh;
    display: flex;
    color: #888;

    .n-select {
      width: 80px;
      margin: auto 1%;
    }

    .selection-right {
      width: 30%;
      height: 25px;
      margin: auto 0 auto auto;
      display: flex;
      justify-content: right;

      .iconfont {
        color: #888;
        font-size: 18px;
        margin: auto 0 auto 6px;
      }
    }

    .e-card {
      background-color: red;

      div {
        .title {
          color: #888;
        }
      }
    }
  }

  .complier-box {
    width: 99%;
    height: 87.4%;
    margin: 0 auto;

    .complier {
      width: 100%;
      height: 100%;
    }
  }

  .submit {
    width: 100%;
    height: 0;
    margin: 0 auto;
    background-color: #fff;
    z-index: 4;
    display: flex;
    flex-direction: column;

    .s-topbar {
      height: 0;
      display: flex;
      justify-content: center;
      position: relative;

      .t-b-bar {
        width: 100%;
        min-height: 6px;
        height: 1%;
        background-color: rgb(230, 230, 230);
        cursor: grab;
        position: absolute;
        top: 0;
        border-radius: 20px;

        &:active {
          background-color: @lowColor;
        }
      }

      .btn {
        position: absolute;
        top: -13px;
        height: 26px;
        width: 26px;
        border-radius: 50%;
        display: flex;
        background-color: #fff;
        box-shadow: rgba(0, 0, 0, 0.1) 0px 2px 6px;
        color: rgb(102, 102, 102);
        cursor: grab;
        z-index: 99;

        .change {
          transform: rotate(180deg);
          transition: 0.3s;
        }

        .unchange {
          transform: rotate(0);
          transition: 0.3s;
        }

        .iconfont {
          margin: auto;
        }
      }
    }

    .s-bar {
      margin: auto 0;
      display: flex;
      width: 100%;
      height: 7vh;
      margin: 0 auto;
    }

    .s-contain {
      width: 98%;
      margin: 0 auto;

      .card2 {
        width: 98%;
        margin: 1vh auto 5vh auto;
        min-height: 30vh;
        border-radius: 5px;
        background-color: #fff;
        box-shadow: 2px 2px 8px rgba(0, 0, 0, 0.1);
        overflow: hidden;
        display: flex;
        flex-direction: column;

        .bar {
          width: 100%;
          height: 6vh;
          margin: 0 auto;
          line-height: 6vh;
          background-color: rgba(0, 0, 0, 0.2);
          font-size: 1rem;
          padding-left: 2vw;
        }

        .contain {
          width: 100%;
          min-height: 20vh;
          font-size: 0.9rem;
          padding: 0.5vh 1vw;

          span {
            white-space: pre-wrap;
          }
        }
      }

      .s-c-scrollbar {
        height: 300px;
      }

      .accept {
        color: rgb(115, 193, 50);
        background-color: rgb(241, 249, 235);
        width: calc(100% - 4vw);
        margin: 2vh auto;
        display: flex;
        flex-direction: column;
        justify-content: center;
        padding: 2vh 1vw;
        border-radius: 10px;

        .a-text {
          font-size: 18px;
          font-weight: 550;
        }

        div {
          margin: 1vh 0;
        }
      }

      .output {
        width: calc(100% - 4vw);
        display: flex;
        margin: 0 auto;
        flex-direction: column;
        margin: 2vh 0;

        .o-text {
          margin: 15px auto;
          width: 100%;
          color: #262626;
          display: flex;
          font-size: 0.9rem;
          line-height: 4vh;
          max-height: 300px;

          .text {
            font-weight: normal;
            font-weight: 0.9rem;
            width: 85%;
            margin: 0 auto;
            max-height: 300px;
            overflow: auto;
            background-color: rgb(248, 248, 248);
            border-radius: 5px;
            line-height: 3vh;
            padding: 4px 1vw;
            white-space: pre-wrap;
            color: #666;
            background-color: @bgColor2;
          }
        }
      }

      .nodata {
        text-align: center;
        width: 100%;
        margin: 10vh auto;
        color: #888;
      }

      .textarea {
        width: 100%;
        margin: 0 0 5vh 0;
      }

      .greenBar {
        color: rgb(115, 193, 50);

        .bar {
          background-color: rgb(241, 249, 235);
        }
      }

      .redBar {
        color: rgb(223, 23, 12);

        .bar {
          background-color: rgb(253, 231, 231);
        }
      }

      .orangeBar {
        color: rgb(225, 167, 67);

        .bar {
          background-color: rgb(252, 246, 236);
        }
      }
    }

    .loading {
      margin: auto 0 auto 1vw;
      min-width: 100px;

      .loading-icon {
        transition: 0.5s;
        animation: rotatee 2s linear infinite;
      }

      @keyframes rotatee {
        0% {
          transform: rotate(0);
        }

        100% {
          transform: rotate(360deg);
        }
      }
    }

    .isLoginPanel {
      height: 2vw;
      line-height: 2vw;
      width: 10vw;
      margin: auto auto auto 3vw;
      background-color: rgb(252, 246, 236);
      text-align: center;
      color: rgb(223, 162, 56);
    }

    .n-btn1 {
      margin: auto 1vw auto auto;
      width: 70px;
    }

    .n-btn2 {
      margin: auto 1vw auto 0;
      width: 70px;
    }
  }
}

::v-deep(.n-card__content) {
  padding: 10px !important;
}

.v-enter-active,
.v-leave-active {
  transition: opacity 0.3s ease;
}

.v-enter-from,
.v-leave-to {
  opacity: 0;
}
</style>

<style>
.el-select__wrapper {
  background-color: rgb(248, 248, 248);
}

.el-textarea__inner {
  background-color: rgb(248, 248, 248);
  height: 20vh;
}
</style>
